package com.computergames.server.service.Implement;

import com.computergames.server.domain.GobangBorad;
import com.computergames.server.message.AbstractGameMessage;
import com.computergames.server.message.chessMessage.AbstractChessMessage;
import com.computergames.server.service.Interface.RuleDetermination;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GobangRuleDetermination implements RuleDetermination {
    private static final GobangRuleDetermination INSTANCE = new GobangRuleDetermination();

    private GobangRuleDetermination() {}

    public static GobangRuleDetermination getInstance() {
        return INSTANCE;
    }

    // 一个房间对应一个棋盘
    private final Map<String, GobangBorad> gobangBoradMap = new ConcurrentHashMap<>();
    /**
     * 规则判断
     *
     * @param content 消息内容
     */
    @Override
    public int ruleDetermination(String roomName, AbstractGameMessage content, ChannelHandlerContext ctx) {
        GobangBorad gobangBorad = gobangBoradMap.computeIfAbsent(roomName, k -> new GobangBorad());
        // 获取坐标字符串，例如 "A5" 或 "C6"
        AbstractChessMessage chessContent = (AbstractChessMessage) content;
        String[] coordinate = chessContent.getCoordinate();

        // 确保坐标字符串不为空且格式正确
        if (coordinate != null && coordinate.length == 1 && coordinate[0].length() == 2
                && Character.isLetter(coordinate[0].charAt(0))
                && Character.isDigit(coordinate[0].charAt(1))) {

            // 分离X坐标（字母）和Y坐标（数字）
            String x = String.valueOf(coordinate[0].charAt(0)); // A, C等
            int y = Integer.parseInt(coordinate[0].substring(1)); // 5, 6等

            // 调用更新棋盘的方法，传入转换后的坐标
            boolean isSuccess = gobangBorad.updateBoard(x, y, chessContent.getChess());

            if (isSuccess) {
                System.out.println("棋子放置成功！");

                // 检查是否获胜
                if (gobangBorad.checkWinCondition(x, y, chessContent.getChess())) {
                    System.out.println("恭喜 " + chessContent.getChess() + " 获胜！");
                    return 1;
                }
                return 0;
            } else {
                System.out.println("放置失败，该位置已有棋子或坐标无效！");
                return -1;
            }
        } else {
            System.out.println("无效的坐标格式！");
            return -1;
        }
    }
}
